<?php
/**
 * 账号
 * 
 * @author kaikaic
 * @date 2018-04-09
 *
 */

namespace app\exam\service;

use service\BasicService;
use think\Db;

class AccountService extends BasicService {

    public function init() {
        $this->dataTable = ['Account', 'AccountExtends'];
    }

    public function importAccount($data) {
        $mobile = $data['mobile'];
        $info = Db::name($this->dataTable[0])->where('mobile', $mobile)->find();
        if ($info) {
            return $info['id'];
        }

        $realName = $userName = $data['user_name'];
        $passInfo = encrypt(substr($mobile,-6),'');
        $params = [
            'mobile' => $mobile,
            'nick_name' => $userName,
            'real_name' => $realName,
            'gender' => $data['gender'],
            'identity_card' => $data['id_card'],
            'password' => $passInfo['pass'],
            'salt' => $passInfo['salt'],
            'create_time' => time()];
        $accountID = Db::name($this->dataTable[0])->insertGetId($params);
        if (!$accountID) {
            return 0;
        }

        $this->initExtends($accountID, $data['birthday'], $data['married']);

        return $accountID;
    }

	public function createUser($userName, $mobile, $realName="") {
	    $info = Db::name($this->dataTable[0])->where('mobile', $mobile)->find();
        if ($info) {
            return $info['id'];
        } else {
            $passInfo = encrypt(substr($mobile,-6),'');
            $data = ['mobile' => $mobile, 'nick_name' => $userName, 'real_name' => $realName, 'password' => $passInfo['pass'], 'salt' => $passInfo['salt'], 'create_time' => time()];
            $accountID = Db::name($this->dataTable[0])->insertGetId($data);

            if (!$accountID) {
                return 0;
            }else {
                $this->initExtends($accountID);

                return $accountID;
            }
        }
    }

    private function initExtends($accountID, $birthday="", $married="") {
        $params = array();
        $params['account_id'] = $accountID;
        $params['province_id'] = 0;
        $params['city_id'] = 0;
        $params['birthday'] = $birthday;
        $params['married'] = $married;
        $params['address'] = "";
        $params['post_code'] = "";

        Db::name($this->dataTable[1])->insertGetId($params);
    }

    public function isMobileExist($mobile) {
        return Db::name($this->dataTable[0])->where("mobile", $mobile)->count();
    }
}

